﻿using Newtonsoft.Json;
using System;
using System.Collections.Generic;
using System.Text;

namespace Admin2020.Core.Helper
{
    public static class JsonHelper
    {
        /// <summary>
        /// 序列化对象
        /// </summary>
        /// <param name="obj">要序列化的对象</param>
        /// <returns>json字符串</returns>
        public static string Serialize(object obj)
        {
            JsonSerializerSettings settings = new JsonSerializerSettings
            {
                ReferenceLoopHandling = ReferenceLoopHandling.Ignore,//忽略循环引用
                DateFormatString = "yyyy-MM-dd HH:mm:ss",
                ContractResolver = new Newtonsoft.Json.Serialization.CamelCasePropertyNamesContractResolver(),//小驼峰
            };

            return JsonConvert.SerializeObject(obj, Formatting.Indented, settings);
        }

        /// <summary>
        /// 反序列化对象
        /// </summary>
        /// <typeparam name="T">要反序列化成的类型</typeparam>
        /// <param name="str">要反序列化的json字符串</param>
        /// <returns>返回T类的实例化对象</returns>
        public static T Deserialize<T>(string str)
        {
            var result = JsonConvert.DeserializeObject<T>(str);
            return result;
        }
    }
}
